﻿
var pageSize = 15;
var selectedParentId = 0;
var arr = [];

$(function () {

    $("#btnAdd").click(function () { Add(); });
    $("#btnDelete").click(function () { DeleteMulti(); });
    $("#btnSave").click(function () { Save(); });
    $("#btnEdit").click(function () { Edit(this); });

    $("#checkAll").click(function () { CheckAll(this); });

    $("#btnDownload").click(function () { Download(this); });

    InitTree();

    $(document).attr("title", "账号");

    $("#treeDiv").height($(window).height() - 190);
    $("#userTable").css("max-height",$(window).height() - 230);

    //LoadTables(1, pageSize);


});


//加载功能树
function InitTree() {
    $.jstree.destroy();
    AjaxData("/Site/GetSiteTreeData?_t=" + new Date().getTime(), "", "Get", null, function (d) {
        if (d.success) {
            var s = '';
            $.each(d.data, function (i, n) {
                putKey(arr, n.parent);
            });

            $.each(d.data, function (i, n) {
                if (!hasKey(arr, n.id)) {
                    s += "<option value=\""+n.id+"\">"+n.text+"</option>";
                }
            });
            $("#SiteId").html(s);

            $('#treeDiv').jstree({       //创建JsTtree
                'core': {
                    'data': d.data,        //绑定JsTree数据
                    "multiple": false    //是否多选
                },
                "plugins": ["state", "types", "wholerow"]  //配置信息
            });

            $("#treeDiv").on("ready.jstree", function (e, data) {   //树创建完成事件
                data.instance.open_all();    //展开所有节点
                if (selectedParentId == 0) {
                    data.instance.select_node(1);
                }
                
            });
            
            /*
            $("#treeDiv").on('changed.jstree', function (e, data) {   //选中节点改变事件

                var node = data.instance.get_node(data.selected[0]);  //获取选中的节点

                if (node) {
                    data.instance.select_node(node.id);
                    selectedParentId = node.id;
                    $("#selSiteId").val(node.id);
                    LoadTables(1, pageSize);

                } 
            });
            */

            $("#treeDiv").on('select_node.jstree', function (e, data) {
                var node = data.instance.get_node(data.selected[0]);  //获取选中的节点

                if (node) {
                    selectedParentId = node.id;
                    $("#selSiteId").val(node.id);
                    LoadTables(1, pageSize);

                } 
            });

        }
    });
}


function putKey(tmp_arr, key) {
    if (key == null || key == undefined) return tmp_arr;
    if (tmp_arr == null || tmp_arr == undefined) {
        tmp_arr = [];
    }

    if (tmp_arr.length > 0) {
        for (var i = 0; i < tmp_arr.length; i++) {
            if (tmp_arr[i] == key) {
                return tmp_arr;
            }
        }
        tmp_arr.push(key);
    } else {
        tmp_arr.push(key);
    }

    return tmp_arr;
}

function hasKey(tmp_arr, key) {
    if (key == null || key == undefined) return false;
    if (tmp_arr == null || tmp_arr == undefined) return false;

    for (var i = 0; i < tmp_arr.length; i++) {
        if (tmp_arr[i] == key) {
            return true;
        }
    }

    return false;
}

//加载列表数据
function LoadTables(startPage, pageSize) {
    $("#tableBody").html("");
    $("#checkAll").prop("checked", false);
    AjaxData("/OddUser/GetAllPageList?startPage=" + startPage + " &pageSize=" + pageSize + "&siteId=" + selectedParentId + "&_t=" + new Date().getTime(), "", "Get", "", function (d) {
        if (d.success) {
            $("#tableBody").html("");
            var data = d.data;
            if (data != null && data.result != null) {
                $.each(data.result, function (i, item) {
                    var tr = '<tr class="oddUserTr">';
                    tr += "<td align='center'><input type='checkbox' class='checkboxs' value='" + item.id + "' /></td>";
                    tr += "<td>" + (pageSize*(startPage-1)+(i + 1)) + "</td>";
                    tr += "<td>" + item.account + "</td>";
                    
                    tr += "<td>" + item.accountBalance + "</td>";
                    
                    tr += "<td>" + item.site.name + "</td>";
                    tr += "<td>" + swapState(item.state) + "</td>";
                    tr += "<td>" + swapNull(item.remark) + "</td>";
                    tr += "</tr>";
                    $("#tableBody").append(tr);
                })

            }

            $(".oddUserTr").on("dblclick", dbClickEdit);

            $("#grid_paging_part").lagerPaper({
                currentIndex: data.pageIndex,
                pageSize: pageSize,
                totalCount: data.totalCount,
                pageCount: data.pageCount,
                onPageChanged: function (e, pageIndex) {
                    LoadTables(pageIndex, pageSize);
                }
            });
        }

    });

}


function dbClickEdit(obj) {
    var id = $(this).children().find("input").val();

    var dialog = $("#editModal").removeClass('hide').dialog({
        modal: true,
        title: '编辑账号',
        title_html: false,
        width: 650,
        height: 560

    });

    $.ajax({
        type: "Get",
        url: "/OddUser/Get?id=" + id + "&_t=" + new Date().getTime(),
        success: function (d) {
            var data = d.data;
            $("#OddUserId").val(data.id);
            $("#Account").val(data.account);
            
            $("#AccountBalance").val(data.accountBalance);
           
            $("#SiteId").val(data.siteId);
            $("#State").val(data.state);
            $("#Remark").val(data.remark);

        }
    })
}


//全选
function CheckAll(obj) {
    $(".checkboxs").each(function () {
        if (obj.checked == true) {
            $(this).prop("checked", true)

        }
        if (obj.checked == false) {
            $(this).prop("checked", false)
        }
    });
};
//新增
function Add() {

    if (!hasKey(arr, selectedParentId)) {
        $("#SiteId").val(selectedParentId);
    }

    var dialog = $("#editModal").removeClass('hide').dialog({
        modal: true,
        title: '新增账号',
        title_html: false,
        width: 650,
        height: 560

    });

    $("#OddUserId").val(-1);
    $("#Account").val("");

    $("#AccountBalance").val("");
  
    $("#State").val("0");
    $("#Remark").val("");


};
//编辑
function Edit(selector) {

    var dialog = $("#editModal").removeClass('hide').dialog({
        modal: true,
        title: '编辑账号',
        title_html: false,
        width: 650,
        height: 560

    });

    var ids = [];
    $(".checkboxs").each(function () {
        if ($(this).prop("checked") == true) {
            ids.push($(this).val());
        }
    });
    if (ids.length == 0) {
        layer.tips("请选择要编辑的记录", selector);
        return;
    };
    if (ids.length > 1) {
        layer.tips("不能同时编辑多条记录", selector);
        return;
    }

    $.ajax({
        type: "Get",
        url: "/OddUser/Get?id=" + ids[0] + "&_t=" + new Date().getTime(),
        success: function (d) {
            var data = d.data;
            $("#OddUserId").val(data.id);
            $("#Account").val(data.account);
           
            $("#AccountBalance").val(data.accountBalance);
           
            $("#SiteId").val(data.siteId);
            $("#State").val(data.state);
            $("#Remark").val(data.remark);
           
        }
    })
};

//保存
function Save() {
    var postData = {
        "dto":
        {
            "Id": $("#OddUserId").val(),
            "Account": $("#Account").val(),
            "AccountBalance": $("#AccountBalance").val(),
            "SiteId": $("#SiteId").val(),
            "State": $("#State").val(),
            "Remark": $("#Remark").val()
        }
    };

    if ($("#Account").val() == "") {
        layer.tips("账号不能为空", "#btnSave");
        return false;
    }

    $.ajax({
        type: "Post",
        url: "/OddUser/Edit",
        data: postData,
        success: function (data) {
            if (data.success) {

                $(".ui-dialog-titlebar-close").trigger("click");
                LoadTables(1, pageSize);
            } else {
                layer.tips(data.message, "#btnSave");
            };
        }
    });
};

//批量删除
function DeleteMulti() {
    var ids = "";
    $(".checkboxs").each(function () {
        if ($(this).prop("checked") == true) {
            ids += $(this).val() + ","
        }
    });
    ids = ids.substring(0, ids.length - 1);
    if (ids.length == 0) {
        layer.alert("请选择要删除的记录。");
        return;
    };
    //询问框
    layer.confirm("您确认删除选定的记录吗？", {
        btn: ["确定", "取消"]
    }, function () {
        var sendData = { "ids": ids };
        $.ajax({
            type: "Post",
            url: "/OddUser/DeleteMuti",
            data: sendData,
            success: function (data) {
                if (data.success) {
                    LoadTables(1, pageSize);
                    layer.closeAll();
                }
                else {
                    layer.alert("删除失败！" + data.message);
                }
            }
        });
    });
};


function Download() {
    $("#btnDownloadFile").click();
};


function swapType(type) {
    if (type == "1") return "发单账号";
    if (type == "2") return "跟单账号";
    return "";
}

function swapState(state) {
    if (state == "0") return "正常";
    if (state == "1") return "禁用";
    return "";
}

function swapNull(str) {
    if (str == null) return "";
    if (str == undefined) return "";
    return str;
}


